package com.idroc.coelacanth.core.dht;

import org.jboss.netty.buffer.ChannelBuffer;

import com.idroc.coelacanth.core.membership.Endpoint;
import com.idroc.coelacanth.core.message.AbstractMessage;

/**
 * 端点转种子节点响应消息
 * @author yuyoo (yuyoo4j@163.com)
 * @date Dec 12, 2009 4:55:31 PM
 */
public class EndpointToNodeResponseMessage extends AbstractMessage {
	
	private int no = -1;
	
	private int nodeType = -1;
	
	private Endpoint candidate = null;
	
	private boolean isOpened = false;

	@Override
	public void decode(ChannelBuffer ib) {

		no = ib.readInt();
		nodeType = ib.readInt(); 
		isOpened = ib.readByte() > 0 ? true : false;
		candidate = new Endpoint();
		candidate.setHost(decodeString(ib));
		candidate.setPort(ib.readInt());
	}

	@Override
	public void encode(ChannelBuffer ob) {

		ob.writeInt(no);
		ob.writeInt(nodeType);
		if (isOpened) {
			ob.writeByte((byte) 1);
		} else {
			ob.writeByte((byte) 0);
		}
		encodeString(ob, candidate.getHost());
		ob.writeInt(candidate.getPort());
	}

	int getNo() {
		return no;
	}

	void setNo(int no) {
		this.no = no;
	}

	public int getNodeType() { 
		return nodeType;
	}

	public void setNodeType(int type) { 
		
		nodeType = type;
	}

	public Endpoint getCandidate() {
		return candidate;
	}

	public void setCandidate(Endpoint candidate) {
		this.candidate = candidate;
	}

	public boolean isOpened() {
		return isOpened;
	}

	void setOpened(boolean isOpened) {
		this.isOpened = isOpened;
	}

	@Override
	public String toString() {

		StringBuilder sb = new StringBuilder();
		sb.append("EndpointToNodeResponseMessage[");
		sb.append("sn:").append(this.getSN()).append(",");
		sb.append("no:").append(no).append(",");
		sb.append("nodeType:").append(nodeType).append(",");
		sb.append("isOpened:").append(isOpened).append(",");
		sb.append("candidate:").append(candidate);
		sb.append("]");
		return sb.toString();
	}

}
